<template>
	<view class="container">
		<!-- <uni-nav-bar class="nav" height="88rpx" leftWidth="0rpx" rightWidth="0rpx" backgroundColor="#ffffff" :border="true" :fixed="true">
			<view class="search-input flex-r">
				<view class="input-view">
					<image src="@/public/images/public/sy_ss.png" mode="aspectFit"></image>
					<input v-model="searchValue" confirm-type="search" @confirm="submitSearch" class="nav-bar-input" type="text" :maxlength="10" placeholder="请输入您要搜索的昵称" :auto-focus="true" :focus="true" />
				</view>
				<view class="search-text flex-r">
					<text @tap="$goBack(1)">取消</text>
				</view>
			</view>
		</uni-nav-bar> -->
		<uni-nav-bar class="nav" height="88rpx" leftWidth="0rpx" rightWidth="0rpx" :backgroundColor="navBgColor" :border="navBorder" :fixed="true">
			<view class="search-view flex-r ac">
				<image class="left" src="@/public/images/public/dhl_fhjt.png" mode="aspectFit" @tap="$goBack(1)"></image>
				<view class="search flex-r ac" :class="{'active': isBlack}">
					<image class="search-icon" src="@/public/images/public/sy_ss.png" mode="aspectFit"></image>
					<input class="search-input text-secondary" v-model="searchValue" type="text" confirm-type="search" :maxlength="10" @confirm="submitSearch" placeholder="请输入您要搜索的昵称" :auto-focus="true" :focus="true" />
					<button class="search-btn text-secondary color-white" @tap="submitSearch">搜索</button>
				</view>
			</view>
		</uni-nav-bar>
		<view class="body">
			<view class="search-head flex-r ac">
				<text class="text-primary text-bold">{{isSearch ? '搜索结果' : '搜索记录'}}</text>
				<template v-if="!isSearch && history[0]">
					<image src="@/public/images/public/qkssjl.png" mode="aspectFit"></image>
					<text class="text-secondary color-grey" @tap="clearHistory">清空搜索记录</text> 
				</template>
			</view>
			<view class="result-body bottom-ios" v-if="isSearch" :class="{'empty': !searchResult[0]}">
				<EmptyContent v-if="!searchResult[0]" top="160rpx" text="搜索结果为空" img="qsy_zwxl" @refresh="submitSearch"></EmptyContent>
				<view class="message-list" v-else>
					<uni-swipe-action>
						<uni-swipe-action-item class="swipe-item" v-for="(msg, index) in searchResult" :key="index">
							<view class="message-item flex-r"
								:id="'msg-' + index"
								:data-index="index"
								:class="{'isPinned': msg.isPinned, 'unread': msg.unreadCount}"
								@tap="goChatBox(msg.conversationID)">
								<view class="left flex-r">
									<lazy-image class="avatar bg" :src="msg.userProfile.avatar+'?imageView2/1/w/100/h/100/q/50'" type="expert" fit="cover"></lazy-image>
									<view class="note" v-if="msg.unreadCount">
										<text>{{msg.unreadCount > 99 ? '···' : msg.unreadCount}}</text>
									</view>
								</view>
								<view class="right flex-r">
									<view class="content flex-c">
										<view class="top flex-r">
											<text class="title">{{msg.userProfile.nick}}</text>
											<text class="time color-grey" v-if="msg.lastMessage.lastTime">{{$CHS.dateFormat(msg.lastMessage.lastTime)}}</text>
										</view>
										<view class="info color-grey" v-if="msg.lastMessage.type == 'TIMTextElem'">
											<template v-for="(item,index) in parseTextMsg(msg.lastMessage)">
												<span v-if="item.name != 'img'" v-html="item.text.replace(/<br>/ig, ' ')"></span>
												<img v-else class="face-message" :src="item.src" style="width: 26rpx;height: 26rpx;object-fit: cover;" />
											</template>
										</view>
										<view class="info color-grey" v-else-if="msg.lastMessage.type == 'TIMCustomElem'">
											{{msg.lastMessage.payload.extension}}
										</view>
										<view class="info color-grey" v-else-if="msg.lastMessage.type == 'TIMFaceElem'">
											{{msg.lastMessage.payload.data}}
										</view>
										<view class="info color-grey" v-else>
											{{msg.lastMessage.messageForShow}}
										</view>
									</view>
								</view>
							</view>
							<template v-slot:right>
								<view class="slot-button flex-r">
									<view class="slot-button-text pinned-msg flex-r ac jc" :class="{'grey': msg.isPinned}" @tap="pinConversation(msg.conversationID, msg.isPinned, index)">
										<text class="text-regular color-white">{{msg.isPinned ? '取消置顶' : '置顶'}}</text>
									</view>
									<view class="slot-button-text delete-msg flex-r ac jc" @tap="delConversation(msg.conversationID, index)">
										<text class="text-regular color-white">删除</text>
									</view>
								</view>
							</template>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
			</view>
			<view class="history" v-else>
				<view class="history-body flex-r"  v-if="!isSearch && history[0]">
					<view class="history-item" v-for="(item, index) in history" :key="index" @tap="goSearch(item)">
						<text class="color-grey">{{item}}</text>
					</view>
				</view>
				<view class="history-empty" v-else>
					<text class="text-secondary color-grey">暂无搜索记录</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import imMsg from "@/utils/common/message.js";
	import {parseText} from "./components/tim-emoji/message-facade.js";
	export default {
		data() {
			return {
				messageLists: [],
				searchResult: [],
				
				searchValue: '',
				history: [],
				
				isSearch: false,
				
				isBlack: false,
				navBgColor: 'rgba(255,255,255,0)',
				navBorder: false
			}
		},
		computed: {
			user() {
				return this.$store.state.user
			},
			imReady() {
				return this.$store.state.imReady
			}
		},
		watch: {
			imReady(newValue, oldValue) {
				if(newValue){
					//获取回话列表
					this.getMsgLists()
				}
			},
			searchValue(newValue, oldValue) {
				if(oldValue && !newValue){
					this.isSearch = false
				}
			}
		},
		onLoad(){
			this.getHistory();
			if(this.imReady){
				this.getMsgLists()
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop
			if(this.timer){
				return false
			}
			this.timer = setTimeout(()=>{
				this.setNavBgColor()
				this.timer = null
			}, 50);
		},
		methods: {
			//提交搜索
			submitSearch() {
				if(this.searchValue.trim() == '' ) {
					uni.showToast({
						title: '关键词不能为空',
						icon: 'none'
					})
					return
				}
				this.searchValue = this.searchValue.trim()
				this.expertLists = []
				this.isSearch = true
				this.isFocus = false
				this.searchMessage();
				this.saveHistory();
			},
			//历史记录点击搜索
			goSearch(key){
				this.searchValue = key;
				this.submitSearch()
			},
			//搜索会话
			searchMessage() {
				if(this.imReady){
					this.searchResult = []
					this.messageLists.every((msg)=>{
						if(msg.userProfile.nick.indexOf(this.searchValue) > -1){
							this.searchResult.push(msg)
						}
						return true
					})
					console.log(this.searchResult);
				}else{
					uni.showToast({
						title: '您的聊天账号已离线',
						icon: 'none'
					})
				}
			},
			//获取历史记录
			getHistory(){
				let value = uni.getStorageSync('historyMessage');
				if(value){
					this.history = JSON.parse(value);
				}
			},
			//保存历史记录
			saveHistory(){
				let historyWords = [];
				let value = uni.getStorageSync('historyMessage');
				if(value){
					value = JSON.parse(value);
					historyWords = value.filter(item => item != this.searchValue); //过滤重复数据
				}
				historyWords.unshift(this.searchValue); //添加到第一个位置
				historyWords.splice(15); //保留15个
				uni.setStorageSync('historyMessage', JSON.stringify(historyWords));//存储列表
				this.history = historyWords;
			},
			//删除历史记录
			clearHistory(){
				this.history = [];
				uni.removeStorageSync('historyMessage');
			},
			//消息列表
			getMsgLists() {
				this.$ShowLoading({show: true})
				imMsg.getMsgList().then((imResponse)=>{
					console.log(imResponse.data);
					this.messageLists = imResponse.data.conversationList
				}).catch((imError)=>{
					console.log(imError);
				}).finally(()=>{
					this.$ShowLoading({show: false})
				})
			},
			//解析表情信息
			parseTextMsg(messsage) {
				return parseText(messsage)
			},
			//进入对话界面
			goChatBox(id){
				if(this.imReady){
					let params = {cid: id}
					this.$goByName('chatbox', params)
				}else{
					this.$ShowToast({text: '您的聊天账号已离线，请刷新网页', type: 2, time: 3})
				}
			},
			//置顶会话
			pinConversation(id, type, index){
				let isPinned = !type
				if(this.imReady){
					imMsg.pinConversation(id, isPinned).then((imResponse)=>{
						console.log(imResponse.data);
						uni.showToast({
							title: isPinned ? '置顶成功' : '取消置顶成功',
							icon: 'success'
						})
						this.searchResult[index].isPinned = isPinned
					}).catch((imError)=>{
						console.log(imError);
						uni.showToast({
							title: '操作失败，请重试',
							icon: 'none'
						})
					})
				}else{
					uni.showToast({
						title: '您的聊天账号已离线',
						icon: 'none'
					})
				}
			},
			//删除会话
			delConversation(id, index){
				if(this.imReady){
					imMsg.deleteConversation(id).then((imResponse)=>{
						console.log(imResponse.data);
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
						this.searchResult.splice(index, 1)
						this.getMsgLists()
					}).catch((imError)=>{
						console.log(imError);
						uni.showToast({
							title: '操作失败，请重试',
							icon: 'none'
						})
					})
				}else{
					uni.showToast({
						title: '您的聊天账号已离线',
						icon: 'none'
					})
				}
			},
			//设置导航区域背景色
			setNavBgColor() {
				let scrollTop = this.scrollTop
				if(scrollTop > 10){
					this.navBorder = true
				}else{
					this.navBorder = false
				}
				switch (true){
					case scrollTop < 10:
						this.navBgColor = 'rgba(255,255,255,0)'
						this.isBlack = false
						break;
					case scrollTop < 20:
						this.navBgColor = 'rgba(255,255,255,0.1)'
						this.isBlack = false
						break;
					case scrollTop < 40:
						this.navBgColor = 'rgba(255,255,255,0.2)'
						this.isBlack = false
						break;
					case scrollTop < 80:
						this.navBgColor = 'rgba(255,255,255,0.4)'
						this.isBlack = true
						break;
					case scrollTop < 120:
						this.navBgColor = 'rgba(255,255,255,0.6)'
						this.isBlack = true
						break;
					case scrollTop < 150:
						this.navBgColor = 'rgba(255,255,255,0.7)'
						this.isBlack = true
						break;
					case scrollTop < 200:
						this.navBgColor = 'rgba(255,255,255,0.8)'
						this.isBlack = true
						break;
					case scrollTop > 300:
						this.navBgColor = 'rgba(255,255,255,1)'
						this.isBlack = true
						break;
				}
			}
		}
	}
</script>

<style lang="scss">
	.container{
		min-height: 100vh;
		.search-view{
			padding: 0 20rpx;
			width: 100%;
			box-sizing: border-box;
			.left{
				width: 48rpx;
				height: 48rpx;
			}
			.search {
				flex: 2;
				height: 72rpx;
				background: #ffffff;
				border-radius: 36rpx;
				&.active{
					background: #F2F5FA;
				}
				.search-icon{
					margin-left: 20rpx;
					width: 32rpx;
					height: 32rpx;
				}
				.search-input {
					flex: 2;
					margin-left: 10rpx;
					height: 72rpx;
					/deep/ .uni-input-placeholder{
						color: #B3B3B3;
					}
				}
				.search-btn{
					margin: 0 6rpx 0 20rpx;
					padding: 0;
					width: 120rpx;
					height: 60rpx;
					background: #0055FF;
					border-radius: 30rpx;
					box-sizing: border-box;
					line-height: 60rpx;
				}
			}
		}
	}
	.body{
		.search-head{
			height: 80rpx;
			padding: 0 20rpx;
			.text-primary{
				flex: 2;
			}
			image{
				margin-right: 10rpx;
				height: 32rpx;
				width: 32rpx;
			}
		}
		.history{
			min-height: calc(var(--safe-height) - #{$navbar-height} - 80rpx);
			background: #FFFFFF;
			.history-body{
				padding: 20rpx 20rpx 0;
				flex-wrap: wrap;
				justify-content: flex-start;
				.history-item{
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 30rpx;
					background: #F2F5FA;
					margin: 0 20rpx 20rpx 0;
					text{
						padding: 0 30rpx;
						font-size: 26rpx;
						line-height: 60rpx;
					}
				}
			}
			.history-empty{
				padding: 20rpx;
			}
		}
		.result-body{
			&.empty{
				background-color: #FFFFFF;
				min-height: calc(var(--safe-height) - #{$navbar-height} - 80rpx);
			}
			.message-list{
				background: #FFFFFF;
				.slot-button{
					width: 320rpx;
					height: 100%;
					.slot-button-text{
						height: 100%;
						width: 50%;
					}
					.pinned-msg{
						background: #4D88FF;
						&.grey{
							background: #a6a6a6;
						}
					}
					.delete-msg{
						background: #FF6674;
					}
				}
				.swipe-item:last-child{
					.message-item{
						.right{
							border-bottom: none;
						}
					}
				}
				.message-item{
					align-items: center;
					padding: 0 0 0 20rpx;
					-webkit-touch-callout: none;
					-webkit-user-select:none;
					-khtml-user-select:none;
					user-select:none;
					&.isPinned{
						background-color: #EDEDED;
					}
					.left{
						align-items: center;
						position: relative;
						padding: 24rpx 0;
						box-sizing: border-box;
						.avatar{
							width: 96rpx;
							height: 96rpx;
							border-radius: 50%;
							&.bg{
								background-color: #FFFFFF;
								background-repeat: no-repeat;
								background-size: 100%;
							}
						}
						.note{
							display: flex;
							align-items: center;
							justify-content: center;
							position: absolute;
							top: 14rpx;
							right: -8rpx;
							background: $uni-primary;
							border-radius: 20rpx;
							padding: 10rpx 14rpx;
							text{
								font-size: 26rpx;
								line-height: 22rpx;
								font-family: Arial;
								color: #FFFFFF;
							}
						}
					}
					.right{
						flex: 2;
						height: 144rpx;
						padding: 0 20rpx;
						border-bottom: 1rpx solid #EDEDED;
						align-items: center;
						.content{
							width: 564rpx;
							.top{
								align-items: center;
								justify-content: space-between;
								margin-bottom: 20rpx;
								.title{
									font-size: 32rpx;
									line-height: 32rpx;
									font-weight: 500;
									color: #333333;
								}
								.time{
									font-size: 24rpx;
									line-height: 24rpx;
									font-family: Arial;
									color: #B3B3B3;
								}
							}
							.info{
								font-size: 26rpx;
								line-height: 26rpx;
								color: #999999;
								width: 564rpx;
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;
								.face-message{
									margin: 0 5rpx;
									width: 26rpx;
									height: 26rpx;
									vertical-align: bottom;
								}
							}
						}
					}
				}
			}
		}
	}
</style>